<script setup lang="ts">
import { GetCountAPI } from '@/services/count'
import {
  GetAccountTypeNameAPI,
  GetGroupAPI,
  GetUserAccountAPI,
  GetUserSettingAPI,
} from '@/services/detail'
import { GetVersionAPI, SearchFileOneAPI } from '@/services/img'
import { useMemberStore } from '@/stores'
import type { GetCountRequest, GetCountResponse } from '@/types/count'
import type { AccountTypeNameResponse, UserAccount, UserSetting } from '@/types/detail'
import type { ZiChanIndexData } from '@/types/zichan'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'

const multiIndex = ref([0, 0, 0])
const newCategotyDataList = ref<string[][]>([[], [], []])
const select = ref('请选择')
const userSetting = ref<UserSetting>()
const version = ref('')
const selectObj = ref({})
const accountTypeNames = ref<AccountTypeNameResponse[]>()
const curAccountTypeName = ref<AccountTypeNameResponse>({
  AccountTypeName: 'ALL',
})
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取会员信息
const memberStore = useMemberStore()
const curUserAccount = ref<UserAccount>()
const userAccounts = ref<UserAccount[]>()
const chartData = ref()
const piechartData = ref()
//支出统计
const opts = {
  color: ['#fdc3bc'],
  padding: [5, 80, 5, 5],
  enableScroll: false,
  legend: {},
  xAxis: {
    disableGrid: true,
    fontSize: 10,
    marginTop: 5,
    rotateLabel: true,
    rotateAngle: 90,
  },
  yAxis: {
    gridType: 'dash',
  },
  extra: {
    bar: {
      type: 'group',
      width: 2,
      meterBorde: 1,
      meterFillColor: '#FFFFFF',
      activeBgColor: '#000000',
      activeBgOpacity: 0.08,
      categoryGap: 2,
    },
  },
}
const opts1 = {
  color: ['#fdc3bc'],
  padding: [15, 15, 15, 15],
  enableScroll: false,
  legend: {},
  xAxis: {
    disableGrid: true,
    fontSize: 10,
    marginTop: 5,
    rotateLabel: true,
    rotateAngle: 90,
  },
  yAxis: {
    gridType: 'dash',
  },
  extra: {},
}
const form = ref<GetCountRequest>({
  Auth: '',
  UserGroup: '',
  InOut: '支出',
  TimeScope: '本月',
  AccountNo: '',
})
const backgroundImgMain = ref('')
const opacity = ref(0.7)
const getCountResponse = ref<GetCountResponse>()
const type = ref('月')
onShow(async () => {
  // const res1 = await GetVersionAPI({
  //   Auth: '',
  // })
  // if (version.value != res1.result.Version) {
  //   window.location.reload()
  // }
  await Refresh()
  //个性主题
  if (memberStore.profile) {
    const detail = await SearchFileOneAPI({
      ImgType: 'count',
      UserName: memberStore.profile.UserName,
      ID: 0,
    })
    if (detail.result) {
      backgroundImgMain.value = detail.result.ImgUrl
    }
    const setting = await GetUserSettingAPI({
      UserName: memberStore.profile.UserName,
    })
    userSetting.value = setting.result
    opacity.value = setting.result.CountOpacit / 10
  }
})
//初始化
onLoad(async () => {
  if (memberStore.profile) {
    await UpdateCookie()
    form.value.Auth = memberStore.profile!.Token
    form.value.UserGroup = memberStore.profile!.UserGroup

    const res1 = await GetVersionAPI({
      Auth: '',
    })
    version.value = res1.result.Version
    //初始化用户账号
    await InitAccountNo()
    //初始化账户
    await InitAccountTypeName()
    //获取当前账户
    GetUserAccount(form.value.AccountNo)

    await Refresh()
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
})
//选择周、月、年
const pickTime = (e: string) => {
  type.value = e
  if (e == '周') {
    form.value.TimeScope = '本周'
  } else if (e == '月') {
    form.value.TimeScope = '本月'
  } else if (e == '年') {
    form.value.TimeScope = '今年'
  }
  Refresh()
}
//选择收入支出
const pickInOut = () => {
  if (form.value.InOut === '收入') form.value.InOut = '支出'
  else form.value.InOut = '收入'
  Refresh()
}
//选择收入支出
const pickTab = (e: string) => {
  form.value.TimeScope = e
  Refresh()
}

//刷新数据
const Refresh = async () => {
  if (memberStore.profile) {
    if (form.value.Auth) {
      const res = await GetCountAPI(form.value)
      getCountResponse.value = res.result
      chartData.value = JSON.parse(JSON.stringify(getCountResponse.value.InOutData))
      piechartData.value = JSON.parse(JSON.stringify(getCountResponse.value.PieData))
      uni.showToast({ icon: 'success', title: '刷新成功' })
    }
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
}
//获取用户账户名
const GetUserAccount = (accountNo: string) => {
  if (memberStore.profile) {
    curUserAccount.value = userAccounts.value?.find((o) => o.AccountNo == accountNo)
  }
}
//初始化账户类型列表
const InitAccountTypeName = async () => {
  if (memberStore.profile) {
    const res = await GetAccountTypeNameAPI({
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push({
      AccountTypeName: 'ALL',
    })
    accountTypeNames.value = res.result
  }
}
//更新cookie
const UpdateCookie = async () => {
  if (memberStore.profile) {
    const res = await GetGroupAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
    })
    memberStore.setProfile(res.result)
  }
}
//初始化账户列表
const InitUserAccount = async () => {
  if (memberStore.profile) {
    const res = await GetUserAccountAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push({
      AccountNo: '',
      UserName: '',
      AccountTypeName: 'ALL',
      AccountCard: 'ALL',
      Display: 'ALL',
      Remark: '',
    })
    userAccounts.value = res.result

    if (userAccounts.value) {
      for (let i = 0; i < userAccounts.value.length; i++) {
        var userName = userAccounts.value[i].UserName
        var exist = newCategotyDataList.value[0].find((o) => o == userName)
        if (!exist) {
          newCategotyDataList.value[0].push(userName)
        }
      }
    }
    var selectUserName = newCategotyDataList.value[0][0]
    InitSelect1(selectUserName)
    var selectAccountTypeName = newCategotyDataList.value[1][0]
    InitSelect2(selectUserName, selectAccountTypeName)
  }
}
//初始化账号下拉选择第二列
const InitSelect1 = (selectUserName: string) => {
  if (userAccounts.value) {
    newCategotyDataList.value[1] = []
    for (let i = 0; i < userAccounts.value.length; i++) {
      var curUserName = userAccounts.value[i].UserName
      var accountTypeName = userAccounts.value[i].AccountTypeName
      if (selectUserName == curUserName) {
        var exist1 = newCategotyDataList.value[1].find((o) => o == accountTypeName)
        if (!exist1) {
          newCategotyDataList.value[1].push(accountTypeName)
        }
      }
    }
  }
}
//初始化账号下拉选择第三列
const InitSelect2 = (selectUserName: string, selectAccountTypeName: string) => {
  if (userAccounts.value) {
    newCategotyDataList.value[2] = []
    for (let i = 0; i < userAccounts.value.length; i++) {
      var curUserName2 = userAccounts.value[i].UserName
      var curAccountTypeName2 = userAccounts.value[i].AccountTypeName
      var accountCard2 = userAccounts.value[i].AccountCard
      if (selectUserName == curUserName2 && selectAccountTypeName == curAccountTypeName2) {
        newCategotyDataList.value[2].push(accountCard2)
      }
    }
  }
}
//初始化用户配置
const InitAccountNo = async () => {
  if (memberStore.profile) {
    const res = await GetUserSettingAPI({ UserName: memberStore.profile.UserName })
    form.value.AccountNo = res.result.DefaultAccountNo
  }
}
//选择账户
const pickerAccountChange = (e: any) => {
  multiIndex.value = e.detail.value
  var selectUserName1 = newCategotyDataList.value[0][multiIndex.value[0]]
  var selectAccountTypeName1 = newCategotyDataList.value[1][multiIndex.value[1]]
  var selectAccount = newCategotyDataList.value[2][multiIndex.value[2]]

  var userAccount = userAccounts.value?.find(
    (o) =>
      o.UserName == selectUserName1 &&
      o.AccountTypeName == selectAccountTypeName1 &&
      o.AccountCard == selectAccount,
  )

  curUserAccount.value = userAccount!
  form.value.AccountNo = curUserAccount.value.AccountNo
  Refresh()
}
//选择账户类型
const pickerAccountTypeChange = (e: any) => {
  const index = e.detail.value as number
  curAccountTypeName.value = accountTypeNames.value![index]
  form.value.AccountNo = curAccountTypeName.value.AccountTypeName
  Refresh()
}
const pickerColumnchange = (e: any) => {
  // 第几列滑动
  // console.log(e.detail.column);
  // 第几列滑动的下标
  // console.log(e.detail.value)
  // 第一列滑动
  if (e.detail.column === 0) {
    multiIndex.value[0] = e.detail.value
    // console.log('第一列滑动');
    var selectUserName = newCategotyDataList.value[0][e.detail.value]
    InitSelect1(selectUserName)
    var selectAccountTypeName = newCategotyDataList.value[1][0]
    InitSelect2(selectUserName, selectAccountTypeName)
    // 第一列滑动  第二列 和第三列 都变为第一个
    multiIndex.value.splice(1, 1, 0)
    multiIndex.value.splice(2, 1, 0)
  }
  // 第二列滑动
  if (e.detail.column === 1) {
    multiIndex.value[1] = e.detail.value
    // console.log('第二列滑动');
    // console.log(this.multiIndex)
    var selectUserName1 = newCategotyDataList.value[0][multiIndex.value[0]]
    var selectAccountTypeName1 = newCategotyDataList.value[1][multiIndex.value[1]]
    InitSelect2(selectUserName1, selectAccountTypeName1)
    // 第二列 滑动 第三列 变成第一个
    multiIndex.value.splice(2, 1, 0)
  }
  // 第三列滑动
  if (e.detail.column === 2) {
    multiIndex.value[2] = e.detail.value
    // console.log('第三列滑动')
    // console.log(this.multiIndex)
  }
}
//修改商品
const OnUpdateGood = async (id: any) => {
  // await UpdateGoodAPI({
  //   ID: goodDetail.value!.ID,
  //   Auth: '07230602',
  //   AccountNo: goodDetail.value!.AccountNo,
  //   Amount: goodDetail.value!.Amount,
  //   IsNotYuSuan: goodDetail.value!.IsNotYuSuan,
  // })
  // popup.value?.close()
  // reFresh()
  uni.reLaunch({
    url: '/pages/NoteAcount/NoteAcount?pageType=update&id=' + id + '&backPage=/pages/count/count',
  })
}
const SearchGoods = async (goodType: string) => {
  const currentDate = new Date()
  const DealYear = currentDate.getFullYear()
  const DealMonth = currentDate.getMonth() + 1
  const inout = form.value.InOut === '收入' ? 1 : 2
  if (type.value == '周') {
    uni.navigateTo({
      url:
        '/pages/count/SearchGoods?GoodsType=' +
        goodType +
        '&DealYear=0' +
        '&Require=' +
        '&DealMonth=0' +
        '&DealDay=0' +
        '&InOut=' +
        inout +
        '&TimeScope=' +
        form.value.TimeScope,
    })
  } else if (type.value == '月') {
    uni.navigateTo({
      url:
        '/pages/count/SearchGoods?GoodsType=' +
        goodType +
        '&DealYear=0' +
        '&Require=' +
        '&DealMonth=0' +
        '&InOut=' +
        inout +
        '&TimeScope=' +
        form.value.TimeScope,
    })
  } else if (type.value == '年') {
    uni.navigateTo({
      url:
        '/pages/count/SearchGoods?GoodsType=' +
        goodType +
        '&DealYear=0' +
        '&Require=' +
        '&DealMonth=0' +
        '&InOut=' +
        inout +
        '&TimeScope=' +
        form.value.TimeScope,
    })
  }
}
const SearchRequireGood = async (require: string) => {
  const currentDate = new Date()
  const DealYear = currentDate.getFullYear()
  const DealMonth = currentDate.getMonth() + 1
  const inout = form.value.InOut === '收入' ? 1 : 2
  if (type.value == '周') {
    uni.navigateTo({
      url:
        '/pages/count/SearchGoods?Require=' +
        require +
        '&GoodsType=' +
        '&DealYear=0' +
        '&DealMonth=0' +
        '&DealDay=0' +
        '&InOut=' +
        inout +
        '&TimeScope=' +
        form.value.TimeScope,
    })
  } else if (type.value == '月') {
    uni.navigateTo({
      url:
        '/pages/count/SearchGoods?Require=' +
        require +
        '&GoodsType=' +
        '&DealYear=0' +
        '&DealMonth=0' +
        '&InOut=' +
        inout +
        '&TimeScope=' +
        form.value.TimeScope,
    })
  } else if (type.value == '年') {
    uni.navigateTo({
      url:
        '/pages/count/SearchGoods?Require=' +
        require +
        '&GoodsType=' +
        '&DealYear=0' +
        '&DealMonth=0' +
        '&InOut=' +
        inout +
        '&TimeScope=' +
        form.value.TimeScope,
    })
  }
}
// 是否触发下拉刷新
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 加载数据
  await Refresh()
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <scroll-view
    v-if="userSetting?.SoftStyle != '简约'"
    enable-back-to-top
    scroll-y
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
  >
    <view class="viewport">
      <view
        class="scroll1"
        :style="`background: url('${backgroundImgMain}')  no-repeat center / cover;opacity: ${opacity}`"
      ></view>
      <view class="header" :style="{ paddingTop: safeAreaInsets!.top + 'px' }">
        <view class="header1">
          <h3 align="center" @tap="pickInOut">{{ form.InOut }}</h3>
          <view class="icon-xiasanjiao"></view>
          <view class="condition">
            <picker
              @change="pickerAccountTypeChange"
              mode="selector"
              :range="accountTypeNames"
              range-key="AccountTypeName"
            >
              <text class="account">{{ curAccountTypeName.AccountTypeName }}</text></picker
            >
          </view>
        </view>
        <view class="header2">
          <text class="item" @tap="pickTime('周')" :class="{ active: type === '周' }">周</text>
          <text class="item" @tap="pickTime('月')" :class="{ active: type === '月' }">月</text>
          <text class="item" @tap="pickTime('年')" :class="{ active: type === '年' }">年</text>
        </view>
      </view>
      <view class="tab" v-if="type === '周'">
        <view class="item" :class="{ active: form.TimeScope === '大前周' }" @tap="pickTab('大前周')"
          >大前周</view
        >
        <view class="item" :class="{ active: form.TimeScope === '前周' }" @tap="pickTab('前周')"
          >前周</view
        >
        <view class="item" :class="{ active: form.TimeScope === '上周' }" @tap="pickTab('上周')"
          >上周</view
        >
        <view class="item" :class="{ active: form.TimeScope === '本周' }" @tap="pickTab('本周')"
          >本周</view
        >
      </view>
      <view class="tab" v-else-if="type === '年'">
        <view class="item" :class="{ active: form.TimeScope === '前年' }" @tap="pickTab('前年')"
          >前年</view
        >
        <view class="item" :class="{ active: form.TimeScope === '上年' }" @tap="pickTab('上年')"
          >上年</view
        >
        <view class="item" :class="{ active: form.TimeScope === '今年' }" @tap="pickTab('今年')"
          >今年</view
        >
      </view>
      <view class="tab" v-else>
        <view class="item" :class="{ active: form.TimeScope === '大前月' }" @tap="pickTab('大前月')"
          >大前月</view
        >
        <view class="item" :class="{ active: form.TimeScope === '前月' }" @tap="pickTab('前月')"
          >前月</view
        >
        <view class="item" :class="{ active: form.TimeScope === '上月' }" @tap="pickTab('上月')"
          >上月</view
        >
        <view class="item" :class="{ active: form.TimeScope === '本月' }" @tap="pickTab('本月')"
          >本月</view
        >
      </view>
      <scroll-view enable-back-to-top scroll-y class="scroll">
        <!-- 总览 -->
        <view class="overview">
          <uni-section :title="form.InOut == '收入' ? '收入总览' : '支出总览'" type="line" />
          <view class="content">
            <view>
              <view class="txt">{{ form.InOut == '收入' ? '总收入' : '总支出' }} </view>
              <view class="val">{{ getCountResponse?.Total }}</view>
            </view>
            <view>
              <view class="txt">日均支出</view>
              <view class="val">{{ getCountResponse?.AmountAvg }}</view>
            </view>
          </view>
        </view>
        <!-- 统计 -->
        <view class="stat">
          <uni-section title="支出统计" type="line" />
        </view>
        <qiun-data-charts class="charts" type="bar" :opts="opts" :chartData="chartData" />
        <!-- 占比 -->
        <view class="gdp">
          <uni-section title="支出占比" type="line" />
          <view class="content"> </view>
        </view>
        <qiun-data-charts class="charts" type="pie" :opts="opts1" :chartData="piechartData" />
        <!-- 刚需&非刚需 -->
        <view class="seq">
          <uni-section title="按刚需分类" type="line" />
          <view class="content" v-for="data in getCountResponse?.RequireData" :key="data.Name">
            <view @tap="SearchRequireGood(data.Name)" class="goodtype">
              <view class="name">
                <view class="circle bold">{{ data.Name.charAt(0) }}</view>
                <view class="name">
                  <view>{{ data.Name }}</view>
                </view>
              </view>
              <view class="goodtypeRight">
                <view>{{ data.Amount }}</view>
                <view class="right">></view>
              </view>
            </view>
          </view>
        </view>
        <!-- 类别 -->
        <view class="seq">
          <uni-section
            :title="form.InOut == '收入' ? '按收入类型排行' : '按支出类型排行'"
            type="line"
          />
          <view
            class="content"
            v-for="data in getCountResponse?.InOutTypeData"
            :key="data.GoodsType"
          >
            <view @tap="SearchGoods(data.GoodsType)" class="goodtype">
              <view class="name">
                <view
                  v-if="data?.GoodsIcon.startsWith('icon')"
                  class="circle"
                  :class="data?.GoodsIcon"
                ></view>
                <view v-else class="circle bold">{{ data?.GoodsIcon }}</view>
                <view>{{ data.GoodsType }}</view>
              </view>
              <view class="goodtypeRight">
                <view>{{ data.Amount }}</view>
                <view class="right">></view>
              </view>
            </view>
          </view>
        </view>
        <!-- 排行 -->
        <view class="seq">
          <uni-section :title="form.InOut == '收入' ? '收入Top' : '支出Top'" type="line" />
          <view class="content" v-for="data in getCountResponse?.InOutTopData" :key="data.ID">
            <view class="name" @tap="OnUpdateGood(data?.ID)">
              <view
                v-if="data?.GoodsIcon.startsWith('icon')"
                class="circle"
                :class="data?.GoodsIcon"
              ></view>
              <view v-else class="circle bold">{{ data?.GoodsIcon }}</view>
              <view>{{ data.Goods }}</view>
              <view class="userName">{{ data.UserName }}</view>
              <view class="userName">{{ data.AccountTypeName }}</view>
            </view>
            <view>{{ data.Amount }}</view>
          </view>
        </view>
      </scroll-view>
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './styles/count.scss';
</style>
